from flask import Flask, render_template, request, jsonify, redirect, url_for, flash, session
from models import db, LotterySettings, LotteryResult, LOTTERY_NUMBERS, validate_id_card, validate_user, get_available_numbers, user_already_participated
import random
import os
from datetime import timedelta

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-change-this'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///lottery.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

def create_tables():
    """创建数据库表"""
    # 删除旧表，重新创建（仅用于开发阶段）
    db.drop_all()
    db.create_all()
    # 创建默认设置
    if not LotterySettings.query.first():
        settings = LotterySettings(is_active=False, round_number=1)
        db.session.add(settings)
        db.session.commit()

@app.route('/')
def index():
    """主页"""
    return render_template('index.html')

@app.route('/control-panel-2024')
def admin():
    """管理员页面"""
    settings = LotterySettings.query.first()
    if not settings:
        settings = LotterySettings(is_active=False, round_number=1)
        db.session.add(settings)
        db.session.commit()
    
    results = LotteryResult.query.filter_by(round_number=settings.round_number).all()
    available_numbers = get_available_numbers(settings.round_number)
    
    return render_template('admin.html', 
                         settings=settings, 
                         results=results,
                         total_numbers=len(LOTTERY_NUMBERS),
                         used_numbers=len(LOTTERY_NUMBERS) - len(available_numbers))

@app.route('/control-panel-2024/toggle_lottery', methods=['POST'])
def toggle_lottery():
    """开启/关闭抽奖"""
    settings = LotterySettings.query.first()
    if not settings:
        settings = LotterySettings(is_active=False, round_number=1)
        db.session.add(settings)
    
    action = request.json.get('action')
    
    if action == 'start':
        settings.is_active = True
    elif action == 'stop':
        settings.is_active = False
    elif action == 'new_round':
        settings.is_active = False
        settings.round_number += 1
    
    db.session.commit()
    
    return jsonify({
        'success': True,
        'is_active': settings.is_active,
        'round_number': settings.round_number
    })

@app.route('/control-panel-2024/results')
def admin_results():
    """获取最新的抽奖结果"""
    settings = LotterySettings.query.first()
    if not settings:
        return jsonify({'results': []})
    
    results = LotteryResult.query.filter_by(round_number=settings.round_number).order_by(LotteryResult.created_at.desc()).all()
    
    results_data = []
    for result in results:
        # 转换为北京时间 (UTC+8)
        beijing_time = result.created_at + timedelta(hours=8)
        results_data.append({
            'name': result.name,
            'gender': result.gender,
            'level': result.level,
            'lottery_number': result.lottery_number,
            'created_at': beijing_time.strftime('%H:%M:%S')
        })
    
    available_numbers = get_available_numbers(settings.round_number)
    
    return jsonify({
        'results': results_data,
        'is_active': settings.is_active,
        'round_number': settings.round_number,
        'total_numbers': len(LOTTERY_NUMBERS),
        'used_numbers': len(LOTTERY_NUMBERS) - len(available_numbers)
    })

@app.route('/lottery')
def lottery():
    """用户抽奖页面"""
    settings = LotterySettings.query.first()
    if not settings or not settings.is_active:
        return render_template('lottery.html', lottery_active=False)
    
    return render_template('lottery.html', lottery_active=True, round_number=settings.round_number)

@app.route('/lottery/status')
def lottery_status():
    """获取抽奖状态"""
    settings = LotterySettings.query.first()
    if not settings:
        return jsonify({'active': False, 'message': '活动未开启'})
    
    return jsonify({
        'active': settings.is_active,
        'round_number': settings.round_number,
        'message': '活动进行中' if settings.is_active else '活动未开启'
    })

@app.route('/lottery/participate', methods=['POST'])
def participate_lottery():
    """参与抽奖"""
    settings = LotterySettings.query.first()
    if not settings or not settings.is_active:
        return jsonify({'success': False, 'message': '抽奖活动未开启'})
    
    data = request.json
    name = data.get('name', '').strip()
    gender = data.get('gender', '').strip()
    level = data.get('level', '').strip()
    id_card = data.get('id_card', '').strip()
    
    # 验证输入
    if not all([name, gender, level, id_card]):
        return jsonify({'success': False, 'message': '请填写完整信息'})
    
    # 验证身份证格式
    if not validate_id_card(id_card):
        return jsonify({'success': False, 'message': '身份证格式不正确'})
    
    # 验证用户是否在白名单中
    if not validate_user(name, gender):
        return jsonify({'success': False, 'message': '用户信息不在允许范围内'})
    
    # 检查用户是否已经参与过当前轮次
    if user_already_participated(name, settings.round_number):
        return jsonify({'success': False, 'message': '您已经参与过本轮抽奖'})
    
    # 特殊规则：申倩固定抽016222
    if name == "申倩":
        lottery_number = "016222"
        # 检查016222是否已被抽取
        existing = LotteryResult.query.filter_by(lottery_number=lottery_number, round_number=settings.round_number).first()
        if existing:
            return jsonify({'success': False, 'message': '您的专属号码已被分配'})
    else:
        # 获取可用号码（排除016222，除非申倩还没抽）
        available_numbers = get_available_numbers(settings.round_number)
        shenqian_participated = user_already_participated("申倩", settings.round_number)
        
        # 如果申倩还没参与，其他人不能抽016222
        if not shenqian_participated and "016222" in available_numbers:
            available_numbers.remove("016222")
        
        if not available_numbers:
            return jsonify({'success': False, 'message': '号码已全部分配完毕'})
        
        lottery_number = random.choice(available_numbers)
    
    # 保存抽奖结果
    result = LotteryResult(
        name=name,
        gender=gender,
        id_card=id_card,
        level=level,
        lottery_number=lottery_number,
        round_number=settings.round_number
    )
    
    db.session.add(result)
    db.session.commit()
    
    return jsonify({
        'success': True,
        'lottery_number': lottery_number,
        'message': f'恭喜您！抽中号码：{lottery_number}'
    })

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        # 创建默认设置
        if not LotterySettings.query.first():
            settings = LotterySettings(is_active=False, round_number=1)
            db.session.add(settings)
            db.session.commit()
    
    app.run(debug=True, host='0.0.0.0', port=5000)
